package com.games.portal.db;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class GamesProvider extends ContentProvider {
	private GamesDatabase mDB;


	public static final String AUTHORITY = "com.games.portal.db.GamesProvider";
	public static final int GAMES = 100;
	public static final int GAME_ID = 110;
	private static final String GAMES_BASE_PATH = "games";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + GAMES_BASE_PATH);
	public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
			+ "/mt-game";
	public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
			+ "/mt-game";

	private static final UriMatcher sURIMatcher = new UriMatcher(
			UriMatcher.NO_MATCH);

	static {
		sURIMatcher.addURI(AUTHORITY, GAMES_BASE_PATH, GAMES);
		sURIMatcher.addURI(AUTHORITY, GAMES_BASE_PATH + "/#", GAME_ID);
	}

	@Override
	public boolean onCreate() {
		mDB = new GamesDatabase(getContext());
		return true;
	}
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
	    int uriType = sURIMatcher.match(uri);
	    SQLiteDatabase sqlDB = mDB.getWritableDatabase();
	    int rowsAffected = 0;
	    switch (uriType) {
	    case GAMES:
	        rowsAffected = sqlDB.delete(GamesDatabase.TABLE_GAMES,
	                selection, selectionArgs);
	        break;
	    case GAME_ID:
	        String id = uri.getLastPathSegment();
	        if (TextUtils.isEmpty(selection)) {
	            rowsAffected = sqlDB.delete(GamesDatabase.TABLE_GAMES,
	            		GamesDatabase.ID + "=" + id, null);
	        } else {
	            rowsAffected = sqlDB.delete(GamesDatabase.TABLE_GAMES,
	                    selection + " and " + GamesDatabase.ID + "=" + id,
	                    selectionArgs);
	        }
	        break;
	    default:
	        throw new IllegalArgumentException("Unknown or Invalid URI " + uri);
	    }
//	    getContext().getContentResolver().notifyChange(uri, null);
	    return rowsAffected;
	}
	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Uri insert(Uri uri, ContentValues contentvalues) {
	       // get database to insert records
		  if(sURIMatcher.match(uri) != GAMES) 
		        throw new IllegalArgumentException("UNKNOWN URI " + uri);

		    ContentValues values;
		    if(contentvalues != null) {
		        values = new ContentValues(contentvalues);
		    } else {
		        values = new ContentValues();
		    }

		    SQLiteDatabase db = mDB.getWritableDatabase();
		    long rowId = db.insert(GamesDatabase.TABLE_GAMES, null, values);

		    Uri returnedUri = null;
	        try {
			    if(rowId > 0) {
			        returnedUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
//			        getContext().getContentResolver().notifyChange(CONTENT_URI, null);
			    } 
	        } finally {
		        db.close();
	        }
	        if (returnedUri == null) {
	        	throw new SQLException("Problem with inserting to DB");
	        }
	        return returnedUri;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		queryBuilder.setTables(GamesDatabase.TABLE_GAMES);
		int uriType = sURIMatcher.match(uri);
		switch (uriType) {
		case GAME_ID:
			queryBuilder.appendWhere(GamesDatabase.ID + "="
					+ uri.getLastPathSegment());
			break;
		case GAMES:
			// no filter
			break;
		default:
			throw new IllegalArgumentException("Unknown URI");
		}
		Cursor cursor = queryBuilder.query(mDB.getReadableDatabase(),
				projection, selection, selectionArgs, null, null, sortOrder);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}
	
    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        SQLiteDatabase db = mDB.getWritableDatabase();
        int count;
        long id;        
        switch (sURIMatcher.match(uri)) {
        case GAMES:
            count = db.update(GamesDatabase.TABLE_GAMES, values, selection, selectionArgs);
            break;
        case GAME_ID:
            id = Long.parseLong(uri.getPathSegments().get(1));
            count = db.update(GamesDatabase.TABLE_GAMES, values, appendRowId(selection, id),
                    selectionArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // Notify any watchers of the change
//        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
    /** Append an id test to a SQL selection expression */
    private String appendRowId(String selection, long id) {
        return GamesDatabase.ID
                + "="
                + id
                + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')'
                        : "");
    }



}